11월 14일 원티드 프리온보딩 백엔드 19일차 TIL
목차
1️⃣ 진행상황
- 텍스트 오디오 파일 생성 구현
2️⃣ 진행상황리뷰
# audio/utils/audio_converter.py
...
def convert_text_to_speech(
text: str,
lang: str = "ko",
slow: bool = False,
__path: str = "audio/storage/",
) -> list[str]:
"""
Split text by sentence and return file paths.
"""
return [
sentence_to_speech_fp(
text=sentence,
lang=lang,
slow=slow,
__path=__path,
)
for sentence in separate_text_by_sentence(text)
]
def sentence_to_speech_fp(
text: str,
lang: str = "ko",
slow: bool = False,
__path: str = "audio/storage/",
) -> str:
"""
If speach file already exists, return file name.
Else, create speach file and return file name.
"""
file_name = (
hashlib.sha256( # create file name by hashing text
text.encode("utf-8")
).hexdigest()
+ ("_slow" if slow else "") # add "_slow" if slow sound
+ ".mp3" # add file extension
)
file_path = Path(__path) / file_name[:6]
Path.mkdir(Path(file_path), exist_ok=True) # create path if not exist
file_path /= file_name[6:]
if file_path.exists():
return file_path
tts = gTTS(text=text, lang=lang, slow=slow)
tts.save(file_path)
return file_path
def separate_text_by_sentence(text: str) -> list[str]:
"""
Separate text by ".", "!", "?" and return list of sentences.
"""
splits = re.split(r"(?![\.\!\?])(?<=[\.\!\?])\s*", text, flags=re.MULTILINE)
# remove empty string
without_empty_str = list(filter(None, splits))
return without_empty_str
separate_text_by_sentence
: 글에서 문장 단위(., !, ?)로 분리하여 리스트로 반환하는 함수sentence_to_speech_fp
: 문장을 음성 파일로 변환하여 저장하고 파일 경로를 반환하는 함수(이미 존재하는 경우 파일 경로만 반환)convert_text_to_speech
: 글을 문장 단위로 음성 파일로 변환하여 저장하고 파일 경로를 반환하는 함수
3️⃣ Today I Learned
RegularExpression
정규표현식. 문자열을 처리하는 방법 중 하나로, 특정한 규칙을 가진 문자열의 집합을 표현하는데 사용된다. 파이썬에선 re
모듈을 사용하여 정규표현식을 사용할 수 있다.
파이썬 정규표현식 문법
여기서는 파이썬에서 사용하는 정규표현식 문법을 요약해서 올릴 것이므로, 자세한 내용은 공식 문서를 참고하자.
|부호|요약|
|:---:|:---|
|.
|모든 문자 매칭|
|^
|문자열의 시작|
|$
|문자열의 끝|
|[
]
|에 속하는 문자라면 모두 매칭|
|[^
]
|에 속하지 않는 문자라면 모두 매칭|
|-
|범위 내 문자 매칭|
|{
}
|직전의 매칭()이 번 반복된 경우 매칭|
|{
,
}
|직전의 매칭()이 번 이상 번 이하 반복된 경우 매칭|
|()
|그룹화|
|*
|={
}
|
|+
|={
}
|
|?
|={
,
}
|
|\|
|또는|
|\
|이스케이프 문자|
이스케이프 문자\
:
|표현식|의미|
|:---:|:---|
|\\
, \.
, \^
, \$
, \+
, \[
, \]
, \{
, \}
, \(
, \)
, \?
, \*
, \\|
|리터럴 문자 자체를 매칭|
|\d
|숫자 매칭, [0-9]
|
|\D
|숫자가 아닌 문자 매칭, [^0-9]
|
|\s
|공백 문자 매칭, [ \t\n\r\f\v]
|
|\S
|공백 문자가 아닌 문자 매칭, [^ \t\n\r\f\v]
|
|\w
|문자 또는 숫자 매칭, 알파벳, 한글, 한자, 가나 등|
이 때 소괄호를 사용한 그룹화를